package com.atgm.mall.gmmallauth.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 全局唯一id
 */
@Component
public class IdGeneratorFactory {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 根据业务key、长度生成唯一id
     * @param key
     * @param length
     * @return
     */
    public String generateIdByToday(String key, Integer length){
        RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        long num = redisAtomicLong.incrementAndGet();
        redisAtomicLong.expireAt(getTodayEndTime());
        String id = getToday() + String.format("%0" + length + "d", num);
        return id;
    }

    /**
     * @Title: getTodayEndTime 获取今日最后的时间
     * @Description: Get the cache expire time.
     * @return
     */
    public static Date getTodayEndTime() {
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.set(Calendar.HOUR_OF_DAY, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        todayEnd.set(Calendar.MILLISECOND, 999);
        return todayEnd.getTime();
    }

    /**
     * @Title: getTodayEndTime 今天的日期格式: 20190101
     * @Description: Get the cache expire time.
     * @return
     */
    public static String getToday() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        return sdf.format(new Date());
    }

}
